import sys
import os

# 添加项目根目录到系统路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from database import Database

class StudentCreator:
    def __init__(self):
        self.db = Database()
    
    def create_student(self, student_id, name, gender, class_name, contact=None):
        """
        创建新学生信息
        
        参数:
            student_id (str): 学号
            name (str): 姓名
            gender (str): 性别
            class_name (str): 班级
            contact (str, optional): 联系方式
        
        返回:
            bool: 创建成功返回True，否则返回False
        """
        try:
            # 验证输入
            if not student_id or not name or not gender or not class_name:
                print("错误：学号、姓名、性别和班级都必须填写")
                return False
            
            if gender not in ['男', '女']:
                print("错误：性别必须是'男'或'女'")
                return False
            
            # 连接数据库
            self.db.connect()
            
            # 检查是否已存在相同学号的学生
            self.db.cursor.execute(
                "SELECT id FROM student WHERE student_id = ?",
                (student_id,)
            )
            if self.db.cursor.fetchone():
                print(f"错误：学号为 {student_id} 的学生已存在")
                self.db.close()
                return False
            
            # 插入新学生
            self.db.cursor.execute(
                "INSERT INTO student (student_id, name, gender, class_name, contact) VALUES (?, ?, ?, ?, ?)",
                (student_id, name, gender, class_name, contact)
            )
            self.db.conn.commit()
            print(f"成功：学生 {name}（学号：{student_id}）创建成功")
            return True
        except Exception as e:
            print(f"错误：创建学生信息时发生错误 - {str(e)}")
            return False
        finally:
            self.db.close()
    
    def batch_create_students(self, students_data):
        """
        批量创建学生信息
        
        参数:
            students_data (list): 学生信息列表，每个元素是包含学生信息的元组
                                (student_id, name, gender, class_name, contact)
        
        返回:
            tuple: (成功创建数量, 总数量)
        """
        success_count = 0
        total_count = len(students_data)
        
        try:
            self.db.connect()
            
            for student_data in students_data:
                student_id, name, gender, class_name, contact = student_data
                
                # 验证输入
                if not student_id or not name or not gender or not class_name:
                    print(f"错误：学生 {name} 的信息不完整，跳过")
                    continue
                
                if gender not in ['男', '女']:
                    print(f"错误：学生 {name} 的性别必须是'男'或'女'，跳过")
                    continue
                
                # 检查是否已存在相同学号的学生
                self.db.cursor.execute(
                    "SELECT id FROM student WHERE student_id = ?",
                    (student_id,)
                )
                if self.db.cursor.fetchone():
                    print(f"错误：学号为 {student_id} 的学生已存在，跳过")
                    continue
                
                # 插入新学生
                self.db.cursor.execute(
                    "INSERT INTO student (student_id, name, gender, class_name, contact) VALUES (?, ?, ?, ?, ?)",
                    (student_id, name, gender, class_name, contact)
                )
                self.db.conn.commit()
                print(f"成功：学生 {name}（学号：{student_id}）创建成功")
                success_count += 1
            
            return success_count, total_count
        except Exception as e:
            print(f"错误：批量创建学生信息时发生错误 - {str(e)}")
            return success_count, total_count
        finally:
            self.db.close()

# 如果直接运行此文件，提供命令行界面
if __name__ == "__main__":
    creator = StudentCreator()
    
    print("===== 学生信息创建 =====")
    print("1. 创建单个学生")
    print("2. 批量创建学生")
    
    choice = input("请选择操作 (1-2): ")
    
    if choice == '1':
        student_id = input("请输入学号: ")
        name = input("请输入姓名: ")
        gender = input("请输入性别 (男/女): ")
        class_name = input("请输入班级: ")
        contact = input("请输入联系方式 (可选): ")
        
        if not contact:
            contact = None
        
        creator.create_student(student_id, name, gender, class_name, contact)
    
    elif choice == '2':
        print("\n批量创建学生信息 (每行输入一个学生信息，格式：学号,姓名,性别,班级,联系方式)")
        print("输入空行结束输入\n")
        
        students_data = []
        while True:
            line = input("> ")
            if not line:
                break
            
            parts = [part.strip() for part in line.split(',')]
            if len(parts) < 4:
                print("错误：输入格式不正确，请确保至少包含学号、姓名、性别和班级")
                continue
            
            student_id = parts[0]
            name = parts[1]
            gender = parts[2]
            class_name = parts[3]
            contact = parts[4] if len(parts) > 4 else None
            
            students_data.append((student_id, name, gender, class_name, contact))
        
        if students_data:
            success_count, total_count = creator.batch_create_students(students_data)
            print(f"\n批量创建完成：成功 {success_count}/{total_count}")
        else:
            print("没有输入任何学生信息")
    
    else:
        print("无效的选择")